package com.yuke.cloud.service.opc.utils;

import com.yuke.cloud.service.opc.entity.FastDFSFile;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;
import java.io.*;

@Slf4j
public class FastDFSClient {

	static {
		try {
			// mod by wg 20181224 如果是生产环境中打包，获取路径时调用getFile()会有FileNotFoundException异常，此时直接设置文件名为路径
//			String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
			String filePath;
			try {
				filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
				log.info("--- filePath : {} ---", filePath);
			} catch (FileNotFoundException e) {
				filePath = "fdfs_client.conf";
			}
			ClientGlobal.init(filePath);
		} catch (Exception e) {
			log.error("FastDFS Client Init Fail!",e);
		}
	}

	public static String[] upload(FastDFSFile file) {
		log.info("----- Enter upload() : File Name: " + file.getName() + "       File Length:" + file.getContent().length);

		NameValuePair[] meta_list = new NameValuePair[2];
		meta_list[0] = new NameValuePair("author", file.getAuthor());
		meta_list[1] = new NameValuePair("fileName", file.getName());
		long startTime = System.currentTimeMillis();
		String[] uploadResults = null;
		StorageClient storageClient=null;
		try {
			storageClient = getTrackerClient();
//			uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
			uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), null);
		} catch (IOException e) {
			log.error("IO Exception when upload the file:" + file.getName(), e);
		} catch (Exception e) {
			log.error("Non IO Exception when upload the file:" + file.getName(), e);
		}
		log.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

		if (uploadResults == null && storageClient!=null) {
			log.error("upload file fail, error code:" + storageClient.getErrorCode());
		}
		String groupName = uploadResults[0];
		String remoteFileName = uploadResults[1];

		log.info("----- Leave upload() : upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
		return uploadResults;
	}

	public static FileInfo getFileInfo(String groupName, String remoteFileName) {
		try {
			StorageClient storageClient = getTrackerClient();
			return storageClient.get_file_info(groupName, remoteFileName);
		} catch (IOException e) {
			log.error("IO Exception: Get File from Fast DFS failed", e);
		} catch (Exception e) {
			log.error("Non IO Exception: Get File from Fast DFS failed", e);
		}
		return null;
	}

	public static InputStream downFile(String groupName, String remoteFileName, String path) {
		try {
			StorageClient storageClient = getTrackerClient();
			byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
			InputStream ins = new ByteArrayInputStream(fileByte);
			FileOutputStream outputStream = new FileOutputStream(new File(path + "\\" + remoteFileName));
			outputStream.write(fileByte);
			outputStream.flush();
			outputStream.close();
			return ins;
		} catch (IOException e) {
			log.error("IO Exception: Get File from Fast DFS failed", e);
		} catch (Exception e) {
			log.error("Non IO Exception: Get File from Fast DFS failed", e);
		}
		return null;
	}

	/**
	 *
	 * @param groupName group1
	 * @param remoteFileName M00/00/08/rBNoJ1wPUKWAacGOAAvqH_kipG8394.jpg
	 * @return -1：失败；0：成功；2：已被删除
	 * @throws Exception
	 */
	public static int deleteFile(String groupName, String remoteFileName)
			throws Exception {
		StorageClient storageClient = getTrackerClient();
		int i = storageClient.delete_file(groupName, remoteFileName);
		//-1：失败；0：成功；2：已被删除
		log.info("{} delete file status :{}({})", remoteFileName, i, i == -1 ? false : true);
		return i;
	}

	public static StorageServer[] getStoreStorages(String groupName)
			throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return trackerClient.getStoreStorages(trackerServer, groupName);
	}

	public static ServerInfo[] getFetchStorages(String groupName,
												String remoteFileName) throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
	}

	public static String getTrackerUrl() throws IOException {
		return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
	}

	private static StorageClient getTrackerClient() throws IOException {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient storageClient = new StorageClient(trackerServer, null);
		return  storageClient;
	}

	private static TrackerServer getTrackerServer() throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return  trackerServer;
	}
}